const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  // 代理 /api 请求到后端，并去掉 /api 前缀
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:8094',
      changeOrigin: true,
      pathRewrite: {
        '^/api': '', // 去掉 /api 前缀
      },
      // 日志记录
      onProxyReq: (proxyReq, req, res) => {
        console.log(`[API Proxy] ${req.method} ${req.url} -> ${proxyReq.path}`);
      },
      onProxyRes: (proxyRes, req, res) => {
        console.log(`[API Proxy] Response: ${proxyRes.statusCode} for ${req.url}`);
      },
      onError: (err, req, res) => {
        console.error(`[API Proxy] Error for ${req.url}:`, err.message);
      },
    })
  );

  // 代理 WebSocket 连接到后端
  app.use(
    '/ws',
    createProxyMiddleware({
      target: 'http://localhost:8094',
      changeOrigin: true,
      ws: true, // 启用WebSocket代理
      // 保持WebSocket路径不变
      pathRewrite: {
        '^/ws': '/ws',
      },
      // WebSocket事件日志
      onProxyReqWs: (proxyReq, req, socket, options, head) => {
        console.log(`[WebSocket Proxy] Upgrading connection: ${req.url}`);
      },
      onProxyRes: (proxyRes, req, res) => {
        console.log(`[WebSocket Proxy] Response: ${proxyRes.statusCode} for ${req.url}`);
      },
      onError: (err, req, res) => {
        console.error(`[WebSocket Proxy] Error for ${req.url}:`, err.message);
      },
      // WebSocket特定配置
      timeout: 0, // 禁用超时，保持长连接
    })
  );
};
